package com.sleep.satokendemo.util;

import cn.hutool.extra.spring.SpringUtil;
import io.lettuce.core.RedisClient;
import lombok.experimental.UtilityClass;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.cache.CacheManager;

import java.util.Objects;
import java.util.Optional;

@UtilityClass
/**
 * @author GuoAo
 * @className RedisUtil
 * @date 2025/2/26
 * @description TODO
 */
public class RedisUtil {

    private static final RedissonClient CLIENT = SpringUtil.getBean(RedissonClient.class);

    private static final CacheManager CACHE_MANAGER = SpringUtil.getBean(CacheManager.class);

    public <T> T get(String key, Class<T> clazz) {
        Object o = Optional.ofNullable(CLIENT.getBucket(key).get()).orElseThrow(() -> new RuntimeException("redis的key不存在！"));
        return clazz.cast(o);
    }

    public <T> void set(String key, T value) {
        RBucket<T> bucket = CLIENT.getBucket(key);
        bucket.set(value);
    }

    public RedissonClient getClient(){
        return CLIENT;
    }

    public void delete(String key){
        CLIENT.getBucket(key).delete();
    }

    public <T> T getCacheName(String cacheName,String key, Class<T> clazz){
        Object o = Optional.ofNullable(CACHE_MANAGER.getCache(cacheName).get(key).get())
                .orElseThrow(() -> new RuntimeException("redis的key不存在！"));
        return clazz.cast(o);
    }

    public <T> void setCacheName(String cacheName,String key, T value){
        Objects.requireNonNull(CACHE_MANAGER.getCache(cacheName)).put(key,value);
    }
}
